package user

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/admin"

	"github.com/gin-gonic/gin"
)

func UpdateUser(c *gin.Context) {
	requestDataStruct := struct {
		Id       int    `json:"id"`
		Username string `json:"username"`
		Password string `json:"password"`
	}{}

	c.ShouldBindJSON(&requestDataStruct)

	update := map[string]interface{}{}

	var adminStruct admin.AdminStruct
	if requestDataStruct.Username != "" {
		exists, err := model.GetModelDataFirst(
			model.Db,
			adminStruct.TableName(),
			&adminStruct,
			model.QueryOptions{
				Conditions: map[string]interface{}{
					"username": requestDataStruct.Username,
					"id != ?":  requestDataStruct.Id,
				},
				Debug: true,
			})

		if exists {
			controller.Fail(c, "当前用户名已存在")
			return
		}

		if err != nil {
			controller.Fail(c, fmt.Sprintf("获取用户信息失败%s", err.Error()))
			return
		}
		update["username"] = requestDataStruct.Username
	}

	//修改了密码
	if requestDataStruct.Password != "" {
		exists, err := model.GetModelDataFirst(
			model.Db,
			adminStruct.TableName(),
			&adminStruct,
			model.QueryOptions{
				Conditions: map[string]interface{}{
					"id": requestDataStruct.Id,
				},
			},
		)

		if !exists {
			controller.Fail(c, "用户不存在")
			return
		}

		if err != nil {
			controller.Fail(c, fmt.Sprintf("获取用户信息失败1%s", err.Error()))
			return
		}

		//生成密码
		data := []byte(requestDataStruct.Password + "|" + adminStruct.Salt)
		hash := md5.Sum(data)
		hashString := hex.EncodeToString(hash[:])

		update["password"] = hashString
	}

	if err := model.UpdateModelData(
		model.Db,
		adminStruct.TableName(),
		map[string]interface{}{
			"id": requestDataStruct.Id,
		},
		update); err != nil {
		controller.Fail(c, fmt.Sprintf("修改用户信息失败%s", err.Error()))
		return
	}

	controller.Success(c, "")
}
